package com.heima.user.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojo.AdUser;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.pojo.ApUserRealname;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.sl.draw.geom.CosExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    //根据状态查询需要认证相关的用户信息
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        // 1 参数检查
        if (dto == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 2 条件查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> iPage = page(page, wrapper);
        // 3 返回结果
        return new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),iPage.getRecords());
    }
    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;

    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 300000)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1.参数检查（实名认证id 不能为空）
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"实名认证id，不能为空");
        }
        //2 根据实名认证id 查询ap_user_realname数据
        ApUserRealname userRealname = getById(dto.getId());
        //3 判断实名认证状态是否为待审核
        if (!AdminConstants.WAIT_AUTH.equals(userRealname.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证的状态不是待审核状态");
        }
        //4 根据实名认证信息关联的apUserId 查询出aepUsr信息
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if (apUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证关联的用户信息不存在");
        }
        //5.修改实名认证状态
        userRealname.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())){
            //驳回原因
            userRealname.setReason(dto.getMsg());
        }
        //修改状态
        updateById(userRealname);
        //6.判断状态是失败还是通过
        if (AdminConstants.FAIL_AUTH.equals(status)){
            return ResponseResult.okResult();
        }
        //7.如果是9代表通过
        if (AdminConstants.PASS_AUTH.equals(status)){
            //8.开通自媒体账号(查询是否已开通)
            WmUser wmUser = createWmUser(apUser);
            //9.开通作者账号
            createApAuthor(apUser,wmUser);
        }
        if (dto.getId().intValue() == 5){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"演示异常，用来测试分布式事务");
        }

        return ResponseResult.okResult();
    }

    /**
     * 4.1 创建自媒体账户
     * @param apUser  APP端用户
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        //1 查询自媒体账号是否存在（APP端用户密码和自媒体密码一致）
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (!result.checkCode()){
            //远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        //获取返回值
        WmUser wmUser = result.getData();
        if (wmUser != null){
            //如果已存在，抛异常结束方法
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"自媒体账户已存在");
        }
        //如果不存在，就保存到数据库
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> save = wemediaFeign.save(wmUser);
        if (!save.checkCode()){
            //远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        return save.getData();
    }

    /**
     * 4.2 创建作者信息
     * @param wmUser
     * @return
     */
    private void createApAuthor(ApUser apUser,WmUser wmUser) {
        //根据用户id，查询作者信息是否存在
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUser.getId());
        if (!result.checkCode()){
            //远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        ApAuthor apAuthor = result.getData();
        if (apAuthor != null){
            //如果作者存在，抛出异常，提示已存在
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已存在");
        }
        //如果作者不存在，创建作者信息，并远程保存
        apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(2);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        ResponseResult<ApAuthor> save = articleFeign.save(apAuthor);
        if (!save.checkCode()){
            //远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }

    }


}
